package com.hzy.yiyaoba.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.hzy.yiyaoba.R;
import com.hzy.yiyaoba.R.id;
import com.hzy.yiyaoba.adapter.LoreClassListAdapter;
import com.hzy.yiyaoba.adapter.LoreListAdapter;
import com.hzy.yiyaoba.bean.Lore;
import com.hzy.yiyaoba.bean.LoreClass;
import com.hzy.yiyaoba.utils.Config;
import com.hzy.yiyaoba.utils.Config.LoreConfig;
import com.hzy.yiyaoba.view.PullToRefreshView;
import com.hzy.yiyaoba.view.PullToRefreshView.OnFooterRefreshListener;
import com.hzy.yiyaoba.view.PullToRefreshView.OnHeaderRefreshListener;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class LoreFragment extends BaseFragment implements OnHeaderRefreshListener, OnFooterRefreshListener, OnClickListener {

	private static final String TAG = getSimpleName(LoreFragment.class);

	public static final int MSG_GET_LORE_CLASS_LIST = 1001;
	public static final int MSG_GET_LORE_LIST = 1002;

	public static final int PAGE = 40;

	private DrawerLayout mDrawLayout;
	private ListView mMainListView;
	private ListView mMenuListView;
	private PullToRefreshView mMainPull;

	private Handler mHandler;
	private List<LoreClass> mLoreClassList;
	private List<Lore> mLoreList;

	private LoreClassListAdapter mLoreClassListAdapter;
	private LoreListAdapter mLoreListAdapter;

	private View mTitleLeftArea;
	private View mMenuProgress;
	private Button mMenuRetry;
	private View mMainProgress;
	private Button mMainRetry;

	private int curLoreClassId = 0;

	@Override
	protected int getLayoutRes() {
		return R.layout.fragment_lore;
	}

	@Override
	protected String getClassName() {
		return TAG;
	}

	@Override
	protected void initEnvironment() {
		mLoreClassList = new ArrayList<LoreClass>();
		mLoreList = new ArrayList<Lore>();
		mLoreListAdapter = new LoreListAdapter(getActivity(), mLoreList);

		mHandler = new Handler(new Callback() {

			@Override
			public boolean handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_GET_LORE_CLASS_LIST:
					onLoreClassSucceed();
					break;
				case MSG_GET_LORE_LIST:
					onLoreSucceed();
				case LoreClassListAdapter.MSG_LORE_CLASS_SELECTED:
					onLoreClassSelected(msg);
					break;
				default:
					break;
				}
				return true;
			}
		});

		mLoreClassListAdapter = new LoreClassListAdapter(getActivity(), mHandler, mLoreClassList);
	}

	private void onLoreClassSelected(Message msg) {
		LoreClass item = (LoreClass) msg.obj;
		if (item != null) {
			mDrawLayout.closeDrawer(Gravity.LEFT);
			curLoreClassId = item.getId();
			downloadLoreList(1, curLoreClassId, true);
		}
	}

	/**
	 * 分类列表下载成功
	 */
	private void onLoreClassSucceed() {
		updateMenuShow(mMenuListView);
		mLoreClassListAdapter.notifyDataSetChanged();
	}

	/**
	 * 分类列表下载失败
	 */
	private void onLoreClassFailed() {
		updateMenuShow(mMenuRetry);
	}

	/**
	 * 内容列表下载成功
	 */
	private void onLoreSucceed() {
		if (mMainPull.isRefreshing()) {
			mMainPull.onFooterRefreshComplete();
			mMainPull.onHeaderRefreshComplete();
		}
		updateMainShow(mMainPull);
		mLoreListAdapter.notifyDataSetChanged();
	}

	/**
	 * 内容列表下载失败
	 */
	private void onLoreFailed() {
		if (mMainPull.isRefreshing()) {
			mMainPull.onFooterRefreshComplete();
			mMainPull.onHeaderRefreshComplete();
		}
		updateMainShow(mMainRetry);
	}

	/**
	 * 只显示参数的view，其他两个隐藏
	 * 
	 * @param v
	 */
	private void updateMenuShow(View v) {
		showView(v, mMenuListView);
		showView(v, mMenuProgress);
		showView(v, mMenuRetry);
	}

	private void updateMainShow(View v) {
		showView(v, mMainPull);
		showView(v, mMainProgress);
		showView(v, mMainRetry);
	}

	@Override
	protected void initView() {

		/** title */
		mTitleLeftArea = findViewById(id.common_fragment_left_area);

		/** menu */
		mDrawLayout = (DrawerLayout) findViewById(id.lore_fragment_drawer);
		mMainListView = (ListView) findViewById(id.lore_fragment_main_list);

		mMenuListView = (ListView) findViewById(id.lore_fragment_menu_list);
		mMenuProgress = findViewById(id.lore_fragment_menu_progress);
		mMenuRetry = (Button) findViewById(id.lore_fragment_menu_retry);
		/** pull to refresh */
		mMainPull = (PullToRefreshView) findViewById(id.lore_fragment_main_refresh);
		mMainProgress = findViewById(id.lore_fragment_main_progress);
		mMainRetry = (Button) findViewById(id.lore_fragment_main_retry);
		/** set listener */
		mMainPull.setOnHeaderRefreshListener(this);
		mMainPull.setOnFooterRefreshListener(this);
		mMenuRetry.setOnClickListener(this);
		mMainRetry.setOnClickListener(this);
		/** set adapter */
		mMenuListView.setAdapter(mLoreClassListAdapter);
		mMainListView.setAdapter(mLoreListAdapter);
		mMainListView.setOnScrollListener(this);
		mTitleLeftArea.setOnClickListener(this);

		downloadLoreClassList();
		downloadLoreList(1, curLoreClassId, true);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (hidden) {
			mDrawLayout.closeDrawers();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case id.common_fragment_left_area:
			performLeftTitleClick();
			break;
		case id.lore_fragment_menu_retry:
			downloadLoreClassList();
			break;
		case id.lore_fragment_main_retry:
			downloadLoreList(1, curLoreClassId, true);
		default:
			break;
		}
	}

	/**
	 * 打开或关闭左边抽屉
	 */
	private void performLeftTitleClick() {
		if (mDrawLayout.isDrawerOpen(Gravity.LEFT)) {
			mDrawLayout.closeDrawer(Gravity.LEFT);
		} else {
			mDrawLayout.openDrawer(Gravity.LEFT);
		}
	}

	/**
	 * 下载分类列表，解析完成后通过Handler回调
	 */
	private void downloadLoreClassList() {
		updateMenuShow(mMenuProgress);
		mHttpUtils.send(HttpMethod.GET, LoreConfig.URL_CLASS, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				new LoreClassParser(responseInfo.result).start();
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				onLoreClassFailed();
			}

			class LoreClassParser extends Thread {

				String mResponse;

				public LoreClassParser(String response) {
					mResponse = response;
				}

				@Override
				public void run() {
					List<LoreClass> temp = null;
					try {
						temp = LoreClass.parseLoreClassList(mResponse);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (temp != null && temp.size() > 0) {
						mLoreClassList.clear();
						addAllLoresClass();
						mLoreClassList.addAll(temp);
						mHandler.sendEmptyMessage(MSG_GET_LORE_CLASS_LIST);
					}
				}
			}
		});
	}

	/**
	 * 在第一项加一个所有分类
	 */
	private void addAllLoresClass() {
		LoreClass loreClass = new LoreClass(0, getString(R.string.common_all_classes));
		mLoreClassList.add(loreClass);
	}

	/**
	 * 下载信息列表
	 * 
	 * @param page
	 *            第几页
	 * @param id
	 *            分类id
	 * @param isClear
	 *            是否清空以前的记录
	 */
	private void downloadLoreList(int page, int id, final boolean isClear) {
		/** 上下拉刷新， 现实刷新区域， 普通刷新，只显示进度圈 */
		if (mMainPull.isRefreshing()) {
			updateMainShow(mMainPull);
		} else {
			updateMainShow(mMainProgress);
		}

		RequestParams params = Lore.createRequestParams(page, PAGE, LoreConfig.TYPE_ID, id);
		mHttpUtils.send(HttpMethod.POST, LoreConfig.URL_LIST, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				new LoreParser(responseInfo.result, isClear).start();
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				onLoreFailed();
			}

			/**
			 * 开一个线程来解json；可能没有必要
			 * 
			 * @author huzongyao
			 * 
			 */
			class LoreParser extends Thread {

				String mResponse;
				private boolean mIsClear;

				public LoreParser(String response, boolean isClear) {
					mResponse = response;
					mIsClear = isClear;
				}

				@Override
				public void run() {
					List<Lore> temp = null;
					try {
						temp = Lore.parseLoreList(mResponse);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (temp != null && temp.size() > 0) {
						if (mIsClear) {
							mLoreList.clear();
						}
						mLoreList.addAll(temp);
						mHandler.sendEmptyMessage(MSG_GET_LORE_LIST);
					}
				}
			}
		});
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		/** 下载首页 */
		downloadLoreList(1, curLoreClassId, true);
		mMainPull.postDelayed(new Runnable() {
			@Override
			public void run() {
				mMainPull.onHeaderRefreshComplete();
			}
		}, Config.REFRESH_TIMEOUT);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		int curPage = mLoreList.size() / PAGE;
		downloadLoreList(curPage + 1, curLoreClassId, false);
		mMainPull.postDelayed(new Runnable() {
			@Override
			public void run() {
				mMainPull.onFooterRefreshComplete();
			}
		}, Config.REFRESH_TIMEOUT);
	}
}
